package com.fingard.csp.common.crypto;

import com.fingard.csp.common.text.StringHelper;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class DigestHelper {
	public static byte[] cryptoMD5(byte[] p_bytes) throws IOException, NoSuchAlgorithmException {
		MessageDigest md5Algorithm = MessageDigest.getInstance("MD5");
		md5Algorithm.update(p_bytes, 0, p_bytes.length);
		return md5Algorithm.digest();
    }
	
	/**生成MD5摘要，返回16进制表示的字符串*/
	public static String cryptoMD5RetHexStr(byte[] p_bytes) throws IOException, NoSuchAlgorithmException {
		byte[] resultBytes = cryptoMD5(p_bytes);
		return StringHelper.bytesToHexString(resultBytes);
    }
	
	/**生成SHA1摘要*/
	public static byte[] cryptoSHA1(byte[] p_bytes) throws Exception{
		MessageDigest sha1Algorithm = MessageDigest.getInstance("SHA1");
		sha1Algorithm.update(p_bytes, 0, p_bytes.length);
		return sha1Algorithm.digest();
    }
	
	/**生成SHA1摘要，返回16进制表示的字符串*/
	public static String cryptoSHA1RetHexStr(byte[] p_bytes) throws Exception{
		byte[] resultBytes = cryptoSHA1(p_bytes);
		return StringHelper.bytesToHexString(resultBytes);
    }

	/**
	 * 产生文件的MD5摘要
	 * @param filePath
	 * @return
	 */
	public static String cryptoMD5ByFilePath(String filePath){
		File file=new File(filePath);
		FileInputStream fis=null;
		try {
			MessageDigest mdg=MessageDigest.getInstance("MD5");
			fis = new FileInputStream(file);
			byte[] buffer=new byte[2048];
			int length=-1;
			while ((length=fis.read(buffer))!=-1){
				mdg.update(buffer,0,length);
			}
			byte[] bytes = mdg.digest();
			return StringHelper.bytesToHexString(bytes);
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			try {
				if(fis!=null){
					fis.close();
				}
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		return null;
	}

	public String buildSendMsg(Map<String,String> map, String saltKey) throws NoSuchAlgorithmException, IOException {
		StringBuilder content = new StringBuilder();
		List<String> keys = new ArrayList<String>(map.keySet());
		Collections.sort(keys);
		int index = 0;
		for (String key : keys) {
			String value = map.get(key);
			if (StringHelper.hasAnyChar(value) && !"sign".equalsIgnoreCase(key)) {
				content.append(index == 0 ? "" : "&").append(key).append("=").append(value);
				index++;
			}
		}

		content.append("&key=" + saltKey);
//		log.info("待签名字符串:\r\n[" + content + "].");
		byte[] tmpDataBytes = content.toString().getBytes("utf-8");
		return DigestHelper.cryptoMD5RetHexStr(tmpDataBytes).toUpperCase();
	}
}
